﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using MicroCenter.Models;

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

using Utils;

namespace MicroCenter.Services
{
    /// <summary>
    /// 文件上传
    /// </summary>
    [Injection(ServiceLifetime.Singleton)]
    public class FileService
    {
        public readonly IWebHostEnvironment webHostEnvironment;


        public readonly GuardianService guardianService;

        /// <summary>
        /// 获取上传目录
        /// </summary>
        /// <returns></returns>
        private string GetRoot()
        {
            var path = Path.Combine(webHostEnvironment.WebRootPath, ConfigConst.UPLOAD_PATH);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            return path;
        }

        /// <summary>
        /// 创建版本
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="versionName"></param>
        public string CreateVersion(string serviceName)
        {
            string versionName = "v1";
            guardianService.Check(serviceName);
            var versions = GetVersions(serviceName);
            if (versions.Length > 0)
                versionName = "v" + (int.Parse(versions.FirstOrDefault().Name.Replace("v", "")) + 1);
            string root = GetRoot();
            string directoryPath = Path.Combine(root, serviceName, versionName);
            Directory.CreateDirectory(directoryPath);
            return versionName;
        }


        public void DeleteVersion(string serviceName, string versionName)
        {
            string root = GetRoot();
            string directoryPath = Path.Combine(root, serviceName, versionName);
            if (Directory.Exists(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }
            else
            {
                throw Error.DefaultError("版本不存在");
            }
        }

        /// <summary>
        /// 获取版本号
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public FileModel[] GetVersions(string serviceName)
        {
            string root = GetRoot();
            string directoryPath = Path.Combine(root, serviceName);
            if (Directory.Exists(directoryPath))
                return new DirectoryInfo(directoryPath).GetDirectories().Select(a => new FileModel()
                {
                    Name = a.Name,
                    CreationTime = a.CreationTime
                }).OrderByDescending(a => a.CreationTime).ToArray();
            return new FileModel[0];
        }

        public void CheckVersion(string serviceName, string version)
        {
            string root = Path.Combine(GetRoot(), serviceName, version);
            if (!Directory.Exists(root))
                throw Error.DefaultError("版本或服务已删除");
            if (Directory.GetFiles(root).Length == 0)
                throw Error.DefaultError("版本中缺少文件");
        }
        public void CopyConfigToRun(string serviceName)
        {
            string root = GetRoot();
            string sourceConfigRoot = Path.Combine(root, serviceName);
            string destRoot = Path.Combine(webHostEnvironment.WebRootPath, ConfigConst.RUN_PATH, serviceName);
            CopyDirectoryAndFiles(sourceConfigRoot, destRoot, false);
        }
        public void CopyToRun(string serviceName, string version)
        {
            string root = GetRoot();
            string sourceRoot = Path.Combine(root, serviceName, version);
            string sourceConfigRoot = Path.Combine(root, serviceName);
            string destRoot = Path.Combine(webHostEnvironment.WebRootPath, ConfigConst.RUN_PATH, serviceName);
            CopyDirectoryAndFiles(sourceRoot, destRoot, true);
            CopyDirectoryAndFiles(sourceConfigRoot, destRoot, false);
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public void Upload(string serviceName, string version, string path, string fileName, long dateTime, Stream stream)
        {
            string root = Path.Combine(GetRoot(), serviceName, version);
            if (!Directory.Exists(root))
                throw Error.DefaultError("版本或服务已删除");
            var directoryPath = Path.Combine(root, path.IfNullOrEmpty("").TrimStart('/'));
            if (!Directory.Exists(directoryPath))
                Directory.CreateDirectory(directoryPath);
            string fullName = Path.Combine(directoryPath, fileName);
            using (FileStream fileStream = new FileStream(fullName, FileMode.OpenOrCreate))
            {
                stream.CopyToAsync(fileStream).GetAwaiter().GetResult();
            }
            if (dateTime > 0)
            {
                File.SetLastWriteTimeUtc(fullName, DateTimeOffset.FromUnixTimeMilliseconds(dateTime).DateTime);
            }
        }

        public void CreateDirectory(string serviceName, string version, string path, string name)
        {
            string root = Path.Combine(GetRoot(), serviceName, version);
            if (!Directory.Exists(root))
                throw Error.DefaultError("版本或服务已删除");
            path = path ?? "";
            string fullName = Path.Combine(root, path.TrimStart('/'), name);
            if (Directory.Exists(fullName))
                throw Error.DefaultError("文件夹已删除");
            Directory.CreateDirectory(fullName);
        }
        public void DeleteFile(string serviceName, string version, string fullName)
        {
            string root = Path.Combine(GetRoot(), serviceName, version, fullName);
            if (!File.Exists(root))
                throw Error.DefaultError("文件已删除");
            File.Delete(root);
        }
        public void DeleteDirectory(string serviceName, string version, string fullName)
        {
            string root = Path.Combine(GetRoot(), serviceName, version ?? "", fullName ?? "");
            if (!Directory.Exists(root))
                throw Error.DefaultError("文件夹已删除");
            Directory.Delete(root, true);
        }

        public List<FileModel> GetDirectoryAndFiles(string serviceName, string version, string path)
        {
            string root = Path.Combine(GetRoot(), serviceName, version);
            if (!Directory.Exists(root))
                throw Error.DefaultError("版本或服务已删除");
            if (path.IsNullOrEmpty())
            {
                path = "";
            }

            var directoryPath = Path.Combine(root, path.TrimStart('/'));
            var directoryInfo = new DirectoryInfo(directoryPath);

            var list = directoryInfo.GetDirectories().Select(a => new FileModel
            {
                IsDirectory = true,
                Name = a.Name,
                LastWriteTime = a.LastWriteTime,
                CreationTime = a.CreationTime,
                FullName = a.FullName.Replace(root, "").Replace('\\', '/').TrimStart('/')
            }).ToList();
            list.AddRange(directoryInfo.GetFiles().Select(a => new FileModel
            {
                Name = a.Name,
                Length = a.Length,
                LastWriteTime = a.LastWriteTime,
                CreationTime = a.CreationTime,
                FullName = a.FullName.Replace(root, "").Replace('\\', '/').TrimStart('/')
            }));
            return list;
        }

        public void UploadConfig(string serviceName, string fileName, Stream stream)
        {
            string root = Path.Combine(GetRoot(), serviceName);
            if (!Directory.Exists(root))
                throw Error.DefaultError("服务不存在");
            string fullName = Path.Combine(root, fileName);

            using FileStream fileStream = new FileStream(fullName, FileMode.OpenOrCreate);
            fileStream.SetLength(0);
            stream.CopyToAsync(fileStream).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public List<FileModel> GetConfigFiles(string serviceName)
        {
            string root = Path.Combine(GetRoot(), serviceName);
            if (!Directory.Exists(root))
                throw Error.DefaultError("服务不存在");

            var directoryInfo = new DirectoryInfo(root);
            return directoryInfo.GetFiles().Select(a => new FileModel
            {
                Name = a.Name,
                Length = a.Length,
                LastWriteTime = a.LastWriteTime,
                CreationTime = a.CreationTime,
                FullName = a.FullName.Replace(root, "").Replace('\\', '/').TrimStart('/')
            }).ToList();
        }

        /// <summary>
        /// 查看配置
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="fullName"></param>
        public string ReadConfig(string serviceName, string fullName)
        {
            if (string.IsNullOrEmpty(serviceName))
            {
                throw new ArgumentException($"“{nameof(serviceName)}”不能为 null 或空。", nameof(serviceName));
            }

            if (string.IsNullOrEmpty(fullName))
            {
                throw new ArgumentException($"“{nameof(fullName)}”不能为 null 或空。", nameof(fullName));
            }
            string root = Path.Combine(GetRoot(), serviceName);
            if (!Directory.Exists(root))
                throw Error.DefaultError("服务不存在");
            string path = Path.Combine(root, fullName);
            if (!File.Exists(path)) throw Error.DefaultError("配置文件不存在");
            return File.ReadAllText(path);
        }

        public void WriteConfig(string serviceName, string fullName, string text)
        {
            if (string.IsNullOrEmpty(serviceName))
            {
                throw new ArgumentException($"“{nameof(serviceName)}”不能为 null 或空。", nameof(serviceName));
            }

            if (string.IsNullOrEmpty(fullName))
            {
                throw new ArgumentException($"“{nameof(fullName)}”不能为 null 或空。", nameof(fullName));
            }
            string root = Path.Combine(GetRoot(), serviceName);
            if (!Directory.Exists(root))
                throw Error.DefaultError("服务不存在");
            string path = Path.Combine(root, fullName);
            if (!File.Exists(path)) throw Error.DefaultError("配置文件不存在");
            File.WriteAllText(path, text);
        }
        public void DeleteConfig(string serviceName, string fullName)
        {
            if (string.IsNullOrEmpty(serviceName))
            {
                throw new ArgumentException($"“{nameof(serviceName)}”不能为 null 或空。", nameof(serviceName));
            }

            if (string.IsNullOrEmpty(fullName))
            {
                throw new ArgumentException($"“{nameof(fullName)}”不能为 null 或空。", nameof(fullName));
            }
            string root = Path.Combine(GetRoot(), serviceName);
            if (!Directory.Exists(root))
                throw Error.DefaultError("服务不存在");
            string path = Path.Combine(root, fullName);
            if (!File.Exists(path)) throw Error.DefaultError("配置文件不存在");
            File.Delete(path);
        }

        private void CopyDirectoryAndFiles(string sourceFolder, string destFolder, bool recursion)
        {
            //如果目标路径不存在,则创建目标路径
            if (!Directory.Exists(destFolder))
            {
                Directory.CreateDirectory(destFolder);
            }
            //得到原文件根目录下的所有文件

            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string fuleName = Path.Combine(destFolder, name);
                    File.Copy(file, fuleName, true);//复制文件
            }
            if (!recursion) return;
            //得到原文件根目录下的所有文件夹
            string[] folders = Directory.GetDirectories(sourceFolder);
            foreach (string folder in folders)
            {
                string name = Path.GetFileName(folder);
                string dest = Path.Combine(destFolder, name);
                CopyDirectoryAndFiles(folder, dest, true);//构建目标路径,递归复制文件
            }
        }


    }

}
